<?php
if($_POST['submit_form']==true){
   //Inicialising the variables
   $name = htmlspecialchars(trim($_POST['name']));
   $descr = htmlspecialchars(trim($_POST['descr']));
   $date_added = time();
   $from_who = $_SESSION['username'];
   
   $sel_t = mysql_query('SELECT * FROM users WHERE username="'.$_SESSION['username'].'"');
   $row_t = mysql_fetch_assoc($sel_t);
   
   //Select the name of the tutorial
   $select_name = mysql_query('SELECT name FROM modules WHERE name = "'.$name.'" && to_tutorial = "'.$row_t['teacher_to'].'"');
   $count = mysql_num_rows($select_name);
   
   //If there is another tutorial with the same name, we stop the code
   if($count != 0){
      echo '<p class="error">Вече съществува такъв раздел към този самоучител!</p>';
   } else {
      //Checking the variables - if they`re empty
      if(empty($name) || empty($descr)){
	     echo '<p class="error">Моля, попълнете ВСИЧКИ полета!</p>';
	  } else {
	  //Checking the length of the variables
      if(strlen($name) < 3) {
	     echo '<p class="error">Кратко име на самоучителя!</p>';
		 $error_name = true;
	  }
	  if(strlen($descr) < 6) {
	     echo '<p class="error">Кратко описание на самоучителя!</p>';
		 $error_descr = true;
	  }
	  
	  //If everything is ok
	   if($error_name != true && $error_descr != true){
	      $insert_tut = mysql_query('INSERT INTO modules(name, descr, date_added, from_who, to_tutorial)
		  VALUES("'.$name.'", "'.$descr.'", '.$date_added.', "'.$from_who.'", "'.$row_t['teacher_to'].'")');
		  if($insert_tut) echo "<p class='success'>Успешен запис!</p>";
	   }
	  }
   }
} else {
   echo '';
}
?>